<template>
  <el-container style="height: 100vh; padding: 20px; background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);">
    <!-- 倒计时弹窗 -->
    <el-dialog
      v-model="showCountdownDialog"
      title="面试准备"
      width="30%"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="false"
    >
      <div style="text-align: center; font-size: 18px;">
        <p v-if="countdownType === 'preparation'">马上开始面试，请做好准备</p>
        <p v-else>下一轮面试将在</p>
        <p>倒计时: {{ countdown }}秒</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="forceStart" v-if="countdown <= 0">
          立即开始
        </el-button>
      </template>
    </el-dialog>

    <!-- 面试轮次控制弹窗 -->
    <el-dialog
      v-model="showRoundControlDialog"
      title="面试轮次控制"
      width="40%"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="false"
    >
      <div class="round-control-content">
        <h2 style="text-align: center; margin-bottom: 30px;">
          <i class="el-icon-medal"></i> 
          第 {{ currentRound }} 轮面试已完成
        </h2>
        
        <div class="round-summary">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-content">
              <div class="summary-item">
                <i class="el-icon-chat-dot-round"></i>
                <span>问题数量: {{ getCurrentRoundQuestions.length }}</span>
              </div>
              <div class="summary-item">
                <i class="el-icon-mic"></i>
                <span>回答数量: {{ getCurrentRoundAnswers.length }}</span>
              </div>
              <div class="summary-item">
                <i class="el-icon-time"></i>
                <span>面试时长: {{ getInterviewDuration }} 分钟</span>
              </div>
            </div>
          </el-card>
        </div>
        
        <div class="next-round-control" v-if="currentRound < totalRounds">
          <h3><i class="el-icon-alarm-clock"></i> 设置下一轮面试时间</h3>
          <div class="interval-selector">
            <el-input-number 
              v-model="selectedInterval" 
              :min="1" 
              :max="60" 
              :step="1" 
              size="large"
              controls-position="right"
            ></el-input-number>
            <span style="margin-left: 10px; font-size: 16px;">分钟</span>
          </div>
        </div>
        
        <div class="final-report" v-else>
          <h3><i class="el-icon-trophy"></i> 恭喜完成全部面试轮次！</h3>
          <p>您已完成全部 {{ totalRounds }} 轮面试</p>
        </div>
      </div>
      
      <template #footer>
        <el-button 
          type="primary" 
          @click="showInterviewReport" 
          class="report-btn"
        >
          <i class="el-icon-document"></i> 查看面试报告
        </el-button>
        <el-button 
          type="success" 
          @click="startNextRound" 
          v-if="currentRound < totalRounds"
          class="next-btn"
        >
          <i class="el-icon-right"></i> 准备下一轮
        </el-button>
        <el-button 
          type="info" 
          @click="finishInterview" 
          v-else
          class="finish-btn"
        >
          <i class="el-icon-finished"></i> 完成面试
        </el-button>
      </template>
    </el-dialog>

    <!-- 左侧面试控制面板 -->
    <el-aside width="400px" class="control-panel">
      <el-card shadow="hover" class="control-card">
        <div class="header">
          <h2 style="color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; margin-bottom: 20px;">
            <i class="el-icon-monitor" style="margin-right: 10px;"></i>
            {{ roundTitle }}
          </h2>
        </div>

        <!-- 面试轮次指示器 -->
        <div class="round-indicator">
          <div 
            v-for="round in totalRounds" 
            :key="round"
            class="round-circle"
            :class="{
              'active': currentRound === round,
              'completed': round < currentRound
            }"
          >
            <span>{{ round }}</span>
            <div class="round-label">第{{ round }}轮</div>
          </div>
        </div>

        <div class="controls">
          <!-- 面试状态控制 -->
          <div class="control-group">
            <el-button 
              type="primary" 
              :disabled="isSessionActive || isInterviewFinished" 
              @click="startInterview"
              class="action-btn"
              icon="el-icon-video-play"
            >
              开始面试
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!isSessionActive"
              @click="endInterview"
              class="action-btn"
              icon="el-icon-switch-button"
            >
              结束面试
            </el-button>
          </div>

          <!-- 语音回答控制 -->
          <div class="control-group" v-if="isSessionActive">
            <el-button 
              @click="toggleAnswering"
              :type="isAnswering ? 'danger' : 'success'"
              :loading="isProcessing"
              class="action-btn"
              :icon="isAnswering ? 'el-icon-microphone' : 'el-icon-turn-off-microphone'"
            >
              {{ isAnswering ? '结束回答' : '开始回答' }}
            </el-button>
          </div>

          <!-- 当前问题区域 -->
          <div v-if="isSessionActive" class="question-card">
            <div class="question-header">
              <h3><i class="el-icon-chat-line-round"></i> 当前问题</h3>
              <el-tag type="info">第{{ currentRound }}轮</el-tag>
              <el-tag type="success" style="margin-left: 5px;">
                问题 {{ currentQuestionIndex + 1 }}/5
              </el-tag>
            </div>
            <div class="current-question">
              {{ currentQuestion }}
            </div>
          </div>
        </div>
      </el-card>
    </el-aside>

    <!-- 主内容区域 -->
    <el-main>
      <el-row :gutter="20" class="video-row">
        <!-- 用户摄像头视图 -->
        <el-col :span="12">
          <el-card shadow="hover" class="camera-panel">
            <div class="panel-header">
              <h3><i class="el-icon-user"></i> 考生视图</h3>
              <el-tag type="success">第{{ currentRound }}轮</el-tag>
              <el-tag type="warning" style="margin-left: 5px;">
                问题 {{ currentQuestionIndex + 1 }}/5
              </el-tag>
            </div>
            <div class="video-container">
              <video 
                ref="videoRef" 
                class="video-stream" 
                autoplay 
                playsinline
                muted  
                v-show="isSessionActive"
              ></video>
              <div v-if="!isSessionActive" class="placeholder">
                <i class="el-icon-camera" style="font-size: 48px; color: #909399;"></i>
                <p>面试开始后将显示摄像头画面</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 数字人视图 -->
        <el-col :span="12">
          <el-card shadow="hover" class="player-panel">
            <div class="panel-header">
              <h3><i class="el-icon-s-custom"></i> 面试官视图</h3>
              <el-tag type="primary">第{{ currentRound }}轮</el-tag>
              <el-tag type="info" style="margin-left: 5px;">
                问题 {{ currentQuestionIndex + 1 }}/5
              </el-tag>
            </div>
            <div class="video-container">
              <div ref="playerContainer" class="player-container" style="width: 100%; height: 500px;"></div>
              <div v-if="!isSessionActive" class="placeholder">
                <i class="el-icon-video-camera" style="font-size: 48px; color: #909399;"></i>
                <p>面试开始后将显示数字人</p>
              </div>
              <div v-if="showResumeButton" class="resume-overlay">
                <el-button type="warning" icon="el-icon-video-play" @click="resumePlayer">
                  点击恢复播放
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElDialog } from 'element-plus'
import axios from 'axios'
import { useInterviewJobStore } from '@/stores/canInterviewJob';
import { useRouter } from 'vue-router';

const router = useRouter();
const canInterviewJob = useInterviewJobStore();

// 定义 RTCPlayer 类型
interface IRTCPlayer {
  on: (event: string, callback: (...args: any[]) => void) => IRTCPlayer;
  resume: () => void;
  destroy: () => void;
  play: () => void;
  playerType?: number;
  stream?: any;
  videoSize?: any;
  container?: HTMLElement | null;
}

// 面试轮次状态
const companySize = ref(canInterviewJob.getInterviewJob().companySize) 
const totalRounds = computed(() => {
  if (companySize.value === '中型公司') {
    return 2 // 中型公司 - 两轮面试
  } else if (companySize.value === '小微企业') {
    return 1 // 小微公司 - 一轮面试
  }
  return 3 // 默认为三轮面试
})
const currentRound = ref(1)
const showRoundControlDialog = ref(false)
const selectedInterval = ref(5) // 默认改为5分钟间隔
const interviewStartTime = ref<Date | null>(null)
const interviewEndTime = ref<Date | null>(null)
const countdownType = ref('preparation') // 'preparation' 或 'interval'
const isInterviewFinished = ref(false) // 添加面试完成状态

// 问题间隔时间配置（毫秒）
const questionInterval = ref(0) // 默认0秒，可配置

// 当前问题索引
const currentQuestionIndex = ref(0)

// 计算轮次标题
const roundTitle = computed(() => {
  const titles = ['模拟一轮面试控制台', '模拟二轮面试控制台', '模拟三轮面试控制台']
  return titles[currentRound.value - 1] || '模拟面试控制台'
})

// 面试状态
const isSessionActive = ref(false)
const isAnswering = ref(false)
const isProcessing = ref(false)
const currentQuestion = ref('请点击"开始面试"按钮启动面试')
const showCountdownDialog = ref(false)
const countdown = ref(9)
let countdownTimer: number | null = null

// 面试官介绍词
const introductions = [
  "您好，我是技术面试官，负责第一轮面试，主要评估您的基础知识掌握情况。",
  "您好，我是部门的产品经理，本轮面试会重点探讨您的知识应用能力，例如案例分析或场景模拟。",
  "您好，我是团队负责人，终轮面试将评估您与岗位的长期匹配度，包括文化适配性和职业规划。"
];

// 面试结束语
const closingStatements = [
  "本次面试到此结束，感谢您的参与。",
  "本轮面试到此结束，感谢您的回答。",
  "终轮面试到此结束，我们会尽快通知您结果。"
];

// 获取职位信息
const jobInfo = computed(() => {
  const job = canInterviewJob.getInterviewJob();
  return {
    jobName: job?.jobType || "软件工程师",
    jobDescription: job?.jobDescription || "负责软件开发和维护",
    requirements: job?.requirements || "熟悉编程基础"
  };
});

// 录音相关
let audioContext: AudioContext | null = null
let processor: ScriptProcessorNode | null = null
let sourceNode: MediaStreamAudioSourceNode | null = null
let audioChunks: Int16Array[] = []
const sampleRate = 16000 // 16kHz采样率

// 摄像头相关
const videoRef = ref<HTMLVideoElement | null>(null)
const mediaStream = ref<MediaStream | null>(null)

// 重构面试记录结构，支持多轮面试
interface InterviewRecord {
  question: string;
  transcription: string;
  snapshot: string;
  expression: { emotion: string; confidence: number } | null;
  speechEvaluation: {
    total_score: string;
    fluency_score: string;
    phone_score: string;
    tone_score: string;
  } | null;
  timestamp: Date;
}

interface InterviewRound {
  round: number;
  startTime: Date;
  endTime: Date | null;
  questions: string[]; // 存储所有问题
  records: InterviewRecord[]; // 存储每个问题的回答记录
}

const interviewRounds = ref<InterviewRound[]>([])

// 获取当前轮次的面试记录
const getCurrentRoundRecords = computed(() => {
  const round = interviewRounds.value.find(r => r.round === currentRound.value)
  return round ? round.records : []
})

// 计算属性来获取当前轮次的问题列表
const getCurrentRoundQuestions = computed(() => {
  const round = interviewRounds.value.find(r => r.round === currentRound.value)
  return round ? round.questions : []
})

// 获取当前轮次的回答列表
const getCurrentRoundAnswers = computed(() => {
  return getCurrentRoundRecords.value.filter(record => record.transcription).map(record => record.transcription)
})

// 计算面试时长（分钟）
const getInterviewDuration = computed(() => {
  if (!interviewStartTime.value || !interviewEndTime.value) return 0
  const duration = (interviewEndTime.value.getTime() - interviewStartTime.value.getTime()) / 1000 / 60
  return Math.round(duration * 10) / 10 // 保留一位小数
})

// 数字人播放器相关
const playerContainer = ref<HTMLElement | null>(null)
const showResumeButton = ref(false)
const streamInfo = ref<any>(null)
const streamPolling = ref<any>(null)

let player: IRTCPlayer | null = null

const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:8080'
const API_ENDPOINTS = {
  START: `${API_BASE}/api/avatar/start`,
  TEXT: `${API_BASE}/api/avatar/text`,
  AUDIO: `${API_BASE}/api/avatar/audio`,
  STOP: `${API_BASE}/api/avatar/stop`,
  MESSAGE: `${API_BASE}/api/avatar/message`,
  MODEL: `${API_BASE}/chat`, // 大模型接口
  FACE_ANALYZE: `${API_BASE}/api/face/analyze`,
  LISTENER: `${API_BASE}/listener`,
  EVALUATE: `${API_BASE}/evaluate` // 新增语音评测接口
};

// 开始面试
const startInterview = async () => {
  try {
    // 在开始新轮次前重置状态
    if (currentRound.value > totalRounds) {
      ElMessage.warning('所有面试轮次已完成，无法再开始新的面试');
      return;
    }
    
    // 初始化摄像头和麦克风 - 关键修改：启用音频处理
    mediaStream.value = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: {
        echoCancellation: true,     // 启用回声消除
        noiseSuppression: true,     // 启用噪声抑制
        autoGainControl: true       // 启用自动增益控制
      }
    })
    
    if (videoRef.value && mediaStream.value) {
      videoRef.value.srcObject = mediaStream.value
    }
    
    // 初始化音频上下文
    audioContext = new (window.AudioContext || (window as any).webkitAudioContext)({
      sampleRate: sampleRate
    })
    
    // 记录面试开始时间
    interviewStartTime.value = new Date()
    
    // 初始化当前轮次记录
    const existingRound = interviewRounds.value.find(r => r.round === currentRound.value)
    if (!existingRound) {
      interviewRounds.value.push({
        round: currentRound.value,
        startTime: new Date(),
        endTime: null,
        questions: [],
        records: []
      })
    }
    
    // 启动数字人会话
    const response = await axios.post(`${API_ENDPOINTS.START}?round=${currentRound.value}`);
    if (response.status === 200) {
      isSessionActive.value = true;
      ElMessage.success(`第${currentRound.value}轮面试已开始`);
      
      // 显示倒计时弹窗
      showCountdownDialog.value = true;
      countdownType.value = 'preparation';
      startCountdown();
      
      // 启动轮询获取推流信息
      startPollingStreamInfo();
    }
  } catch (error: any) {
    console.error('启动面试失败', error);
    ElMessage.error(`启动面试失败: ${error.response?.data || error.message}`);
  }
}

// 倒计时方法
const startCountdown = () => {
  countdown.value = 9;
  countdownTimer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer as number);
      generateQuestions();
      showCountdownDialog.value = false;
    }
  }, 1000);
}

// 强制开始方法
const forceStart = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  countdown.value = 0;
  generateQuestions();
  showCountdownDialog.value = false;
}

// 结束面试
const endInterview = async () => {
  try {
    // 停止数字人会话
    const response = await axios.post(API_ENDPOINTS.STOP);
    if (response.status === 200) {
      isSessionActive.value = false;
      ElMessage.success(`第${currentRound.value}轮面试已结束`);
      
      // 记录面试结束时间
      interviewEndTime.value = new Date()
      
      // 更新当前轮次记录
      const currentRoundIndex = interviewRounds.value.findIndex(r => r.round === currentRound.value)
      if (currentRoundIndex !== -1) {
        interviewRounds.value[currentRoundIndex].endTime = new Date()
      }
      
      // 停止轮询
      clearInterval(streamPolling.value);
      
      // 重置推流信息
      streamInfo.value = null;
      
      // 显示轮次控制对话框
      showRoundControlDialog.value = true;
    }
    
    // 清理资源
    if (mediaStream.value) {
      mediaStream.value.getTracks().forEach(track => track.stop())
    }
    
    if (audioContext) {
      audioContext.close()
    }
    
    if (player) {
      player.destroy();
      player = null;
    }
  } catch (error: any) {
    console.error('结束面试失败', error);
    ElMessage.error(`结束面试失败: ${error.response?.data || error.message}`);
  }
}

// 开始下一轮面试
const startNextRound = () => {
  showRoundControlDialog.value = false;
  
  // 重置问题索引
  currentQuestionIndex.value = 0;
  
  // 设置倒计时类型为间隔倒计时
  countdownType.value = 'interval';
  countdown.value = selectedInterval.value * 60; // 转换为秒
  showCountdownDialog.value = true;
  
  // 开始倒计时
  countdownTimer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer as number);
      showCountdownDialog.value = false;
      
      // 进入下一轮
      currentRound.value++;
      startInterview();
    }
  }, 1000);
}

// 完成面试
const finishInterview = () => {
  showRoundControlDialog.value = false;
  // 标记面试已完成
  isInterviewFinished.value = true;
  ElMessage.success('所有面试轮次已完成');
}

// 显示面试报告（跳转到新页面）
const showInterviewReport = () => {
  // 保存面试数据到store
  canInterviewJob.setInterviewReport({
    rounds: interviewRounds.value,
    startTime: interviewStartTime.value,
    endTime: interviewEndTime.value,
    jobInfo: jobInfo.value
  });
  
  // 关闭对话框
  showRoundControlDialog.value = false;
  
  // 跳转到面试报告页面
  router.push({ name: 'InterviewResult' });
}

// 切换回答状态
const toggleAnswering = () => {
  if (isAnswering.value) {
    stopRecording()
  } else {
    startRecording()
  }
  isAnswering.value = !isAnswering.value
}

// 开始录音
const startRecording = () => {
  if (!mediaStream.value || !audioContext) return
  
  audioChunks = []
  
  // 创建音频源节点
  sourceNode = audioContext.createMediaStreamSource(mediaStream.value)
  
  // 创建处理器节点
  processor = audioContext.createScriptProcessor(4096, 1, 1)
  
  processor.onaudioprocess = (e) => {
    const inputData = e.inputBuffer.getChannelData(0)
    const output = new Int16Array(inputData.length)
    
    // 将Float32转换为Int16
    for (let i = 0; i < inputData.length; i++) {
      output[i] = Math.max(-1, Math.min(1, inputData[i])) * 32767
    }
    
    audioChunks.push(output)
  }
  
  // 连接节点
  sourceNode.connect(processor)
  processor.connect(audioContext.destination)
  
  // 在开始回答时进行表情分析
  takeSnapshotAndAnalyze();
  
  ElMessage.info('开始录音，请回答问题...');
}

// 停止录音并进行语音评测
const stopRecording = async () => {
  if (!processor || !sourceNode) return

  isProcessing.value = true
  ElMessage.info('正在处理您的回答...')

  try {
    // 合并所有音频数据
    const totalLength = audioChunks.reduce((acc, chunk) => acc + chunk.length, 0)
    const mergedData = new Int16Array(totalLength)
    let offset = 0

    for (const chunk of audioChunks) {
      mergedData.set(chunk, offset)
      offset += chunk.length
    }

    // 创建PCM文件
    const pcmBlob = new Blob([mergedData.buffer], { type: 'audio/pcm' })
    const file = new File([pcmBlob], 'interview_response.pcm', { type: 'audio/pcm' })

    // 上传识别
    const formData = new FormData()
    formData.append('file', file)

    // 语音识别请求
    const recognitionResponse = await fetch(API_ENDPOINTS.LISTENER, {
      method: 'POST',
      body: formData
    })

    const recognitionData = await recognitionResponse.json()
    const transcription = recognitionData.msg || '识别失败'

    // 获取当前轮次记录索引
    const currentRoundIndex = interviewRounds.value.findIndex(r => r.round === currentRound.value)

    if (currentRoundIndex !== -1) {
      // 添加回答记录
      const recordIndex = interviewRounds.value[currentRoundIndex].records.length
      interviewRounds.value[currentRoundIndex].records.push({
        question: currentQuestion.value,
        transcription: transcription,
        snapshot: '',
        expression: null,
        speechEvaluation: null,
        timestamp: new Date()
      })

      // 语音评测请求 - 修复：使用识别结果(transcription)作为评测文本
      const evaluationFormData = new FormData()
      evaluationFormData.append('audio', file)
      evaluationFormData.append('text', transcription) // 使用识别结果而不是问题文本

      const evaluationResponse = await fetch(API_ENDPOINTS.EVALUATE, {
        method: 'POST',
        body: evaluationFormData
      })

      if (!evaluationResponse.ok) {
        throw new Error('语音评测请求失败')
      }

      const responseText = await evaluationResponse.text()
      const parser = new DOMParser()
      const xmlDoc = parser.parseFromString(responseText, "text/xml")
      const readSentence = xmlDoc.querySelector('read_sentence[accuracy_score]')

      if (readSentence) {
        // 保存评测结果
        interviewRounds.value[currentRoundIndex].records[recordIndex].speechEvaluation = {
          total_score: readSentence.getAttribute('total_score'),
          fluency_score: readSentence.getAttribute('fluency_score'),
          phone_score: readSentence.getAttribute('phone_score'),
          tone_score: readSentence.getAttribute('tone_score')
        }
      }
    }

    ElMessage.success('回答已记录')

    // 检查是否是最后一个问题
    const currentRoundQuestions = getCurrentRoundQuestions.value
    const isLastQuestion = currentQuestionIndex.value >= currentRoundQuestions.length - 1

    // 如果是最后一个问题，确保表情分析完成后再结束面试
    if (isLastQuestion) {
      try {
        // 确保最后一次回答的表情分析完成
        await takeSnapshotAndAnalyze()
        
        // 发送面试结束语
        const closingIndex = currentRound.value - 1;
        if (closingIndex < closingStatements.length) {
          await sendTextToAvatar(closingStatements[closingIndex], currentRound.value);
          // 等待结束语说完
          await new Promise(resolve => setTimeout(resolve, 3000));
        }
        
        // 延迟1秒让用户看到完成提示
        setTimeout(() => {
          endInterview()
        }, 1000)
      } catch (error) {
        console.error('最后一次表情分析失败:', error)
        endInterview() // 即使分析失败也继续结束流程
      }
    } else {
      // 不是最后一个问题，正常进入下一题
      setTimeout(() => {
        if (isSessionActive.value) {
          showNextQuestion()
        }
      }, questionInterval.value)
    }

  } catch (error) {
    console.error('录音处理失败:', error)
    ElMessage.error('回答处理失败，请重试')
  } finally {
    isProcessing.value = false
  }
}

// 显示下一个问题
const showNextQuestion = async () => {
  currentQuestionIndex.value++;
  
  // 获取当前轮次的问题列表
  const currentRoundQuestions = getCurrentRoundQuestions.value;
  
  if (currentQuestionIndex.value < currentRoundQuestions.length) {
    // 设置当前问题
    currentQuestion.value = currentRoundQuestions[currentQuestionIndex.value];
    
    // 将问题发送给数字人
    await sendTextToAvatar(currentQuestion.value, currentRound.value);
    
    ElMessage.info('下一个问题已准备');
  }
}

// 增强的 takeSnapshotAndAnalyze 方法
const takeSnapshotAndAnalyze = async (): Promise<boolean> => {
  if (!isSessionActive.value) return false

  try {
    const snapshot = takeSnapshot()
    if (!snapshot) return false

    // 将base64转换为Blob
    const blob = await fetch(snapshot).then(r => r.blob())
    const file = new File([blob], 'snapshot.jpg', { type: 'image/jpeg' })

    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch(API_ENDPOINTS.FACE_ANALYZE, {
      method: 'POST',
      body: formData
    })

    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)

    const data = await response.json()
    console.log('表情分析结果:', data) // 调试日志

    // 解析表情数据
    const expression = parseFaceResult(data.payload.face_detect_result.text)

    // 获取当前轮次记录索引
    const currentRoundIndex = interviewRounds.value.findIndex(r => r.round === currentRound.value)

    // 更新最近的记录
    if (currentRoundIndex !== -1 && interviewRounds.value[currentRoundIndex].records.length > 0) {
      const lastIndex = interviewRounds.value[currentRoundIndex].records.length - 1
      interviewRounds.value[currentRoundIndex].records[lastIndex] = {
        ...interviewRounds.value[currentRoundIndex].records[lastIndex],
        snapshot: snapshot,
        expression: {
          emotion: expression.emotion,
          confidence: expression.confidence
        }
      }
    }

    return true
  } catch (error) {
    console.error('表情分析失败:', error)
    ElMessage.warning('表情分析失败，将继续记录回答')
    return false
  }
}

// 解析人脸结果
const parseFaceResult = (base64Str: string) => {
  const EMOTION_MAP = ['惊讶', '害怕', '厌恶', '高兴', '悲伤', '生气', '正常']
  
  const decodedStr = atob(base64Str)
  const jsonData = JSON.parse(decodedStr)
  
  if (jsonData.face_num < 1) {
    throw new Error('未检测到人脸')
  }
  
  const firstFace = jsonData['face_1']
  if (!firstFace?.property) {
    throw new Error('人脸数据格式异常')
  }
  
  const expression = firstFace.property.expression
  if (typeof expression !== 'number' || expression < 0 || expression > 6) {
    throw new Error(`无效的表情编号：${expression}`)
  }
  
  return {
    emotion: EMOTION_MAP[expression] || '未知表情',
    confidence: Math.round(firstFace.score * 100)
  }
}

// 截图功能
const takeSnapshot = (): string => {
  if (!videoRef.value) return ''
  
  const canvas = document.createElement('canvas')
  canvas.width = videoRef.value.videoWidth
  canvas.height = videoRef.value.videoHeight
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return ''
  
  ctx.drawImage(videoRef.value, 0, 0)
  return canvas.toDataURL('image/jpeg')
}

// 生成面试问题
const generateQuestions = async () => {
  try {
    ElMessage.info('正在生成面试问题...');
    
    // 重置问题索引
    currentQuestionIndex.value = 0;
    
    // 根据公司规模和当前轮次生成不同的提示词
    let prompt = "";
    
    if (companySize.value === 'medium') {
      // 中型公司 - 两轮面试
      if (currentRound.value === 1) {
        // 第一轮包含case1和case2
        prompt = `角色：专业第一轮面试官
行为模式：
1. 根据候选人的岗位（${jobInfo.value.jobName}），准备5个关于专业基础知识和应用能力的问题
2. 一次性返回5个问题，每个问题一行
3. 问题间不要有序号

请生成5个问题，问题应聚焦于${jobInfo.value.jobName}岗位：
- 职位描述：${jobInfo.value.jobDescription}
- 岗位要求：${jobInfo.value.requirements}

问题要求：
1. 问题应包含基础概念、原理或术语
2. 问题应设计为实际应用场景
3. 问题应考察解决问题的能力
4. 问题应适度挑战候选人的应用能力`;
      } else {
        // 第二轮为case3
        prompt = `角色：专业第三轮面试官
行为模式：
1. 根据候选人的岗位（${jobInfo.value.jobName}），准备5个关于岗位匹配度的问题
2. 一次性返回5个问题，每个问题一行
3. 问题间不要有序号

请生成5个问题，问题应聚焦于${jobInfo.value.jobName}岗位的匹配度：
- 职位描述：${jobInfo.value.jobDescription}
- 岗位要求：${jobInfo.value.requirements}

问题要求：
1. 问题应考察职业素养和团队协作
2. 问题应关注岗位契合度和职业规划
3. 问题应评估解决实际工作挑战的能力
4. 问题应包含对岗位理解的考察`;
      }
    } else if (companySize.value === 'small') {
      // 小微公司 - 一轮面试，包含case1、case2和case3
      prompt = `角色：专业综合面试官
行为模式：
1. 根据候选人的岗位（${jobInfo.value.jobName}），准备5个综合性的问题
2. 一次性返回5个问题，每个问题一行
3. 问题间不要有序号

请生成5个问题，问题应聚焦于${jobInfo.value.jobName}岗位：
- 职位描述：${jobInfo.value.jobDescription}
- 岗位要求：${jobInfo.value.requirements}

问题要求：
1. 问题应包含基础概念、原理或术语
2. 问题应设计为实际应用场景
3. 问题应考察解决问题的能力
4. 问题应评估解决实际工作挑战的能力
5. 问题应包含对岗位理解的考察`;
    } else {
      // 大型公司 - 保持原有逻辑
      switch(currentRound.value) {
        case 1: // 第一轮：知识掌握程度
          prompt = `角色：专业第一轮面试官
行为模式：
1. 根据候选人的岗位（${jobInfo.value.jobName}），准备5个关于专业基础知识的问题
2. 一次性返回5个问题，每个问题一行
3. 问题间不要有序号

请生成5个问题，问题应聚焦于${jobInfo.value.jobName}岗位的基础知识：
- 职位描述：${jobInfo.value.jobDescription}
- 岗位要求：${jobInfo.value.requirements}

问题要求：
1. 问题应简洁明确，只包含单个问题
2. 问题应针对基础概念、原理或术语
3. 问题难度应适中，适合评估基础知识掌握程度`;
          break;
          
        case 2: // 第二轮：知识的应用能力
          prompt = `角色：专业第二轮面试官
行为模式：
1. 根据候选人的岗位（${jobInfo.value.jobName}），准备5个关于知识应用能力的问题
2. 一次性返回5个问题，每个问题一行
3. 问题间不要有序号

请生成5个问题，问题应聚焦于${jobInfo.value.jobName}岗位的知识应用能力：
- 职位描述：${jobInfo.value.jobDescription}
- 岗位要求：${jobInfo.value.requirements}

问题要求：
1. 问题应设计为实际应用场景
2. 问题应考察解决问题的能力
3. 问题应要求候选人解释思路或方法
4. 问题应适度挑战候选人的应用能力`;
          break;
          
        case 3: // 第三轮：岗位相关问题
          prompt = `角色：专业第三轮面试官
行为模式：
1. 根据候选人的岗位（${jobInfo.value.jobName}），准备5个关于岗位匹配度的问题
2. 一次性返回5个问题，每个问题一行
3. 问题间不要有序号

请生成5个问题，问题应聚焦于${jobInfo.value.jobName}岗位的匹配度：
- 职位描述：${jobInfo.value.jobDescription}
- 岗位要求：${jobInfo.value.requirements}

问题要求：
1. 问题应考察职业素养和团队协作
2. 问题应关注岗位契合度和职业规划
3. 问题应评估解决实际工作挑战的能力
4. 问题应包含对岗位理解的考察`;
      }
    }
    
    // 发送面试官介绍
    const introIndex = currentRound.value - 1;
    if (introIndex < introductions.length) {
      // 在介绍期间，设置当前问题为提示信息
      currentQuestion.value = '面试官正在自我介绍...';
      // 发送介绍词
      await sendTextToAvatar(introductions[introIndex], currentRound.value);
      // 等待介绍词说完
      await new Promise(resolve => setTimeout(resolve, 4000));
    }
    
    // 获取大模型响应
    const modelContent = await getModelResponse(prompt);
    
    if (modelContent) {
      // 将返回的内容按换行分割成数组
      const questions = modelContent.split('\n').filter(q => q.trim() !== '');
      
      // 获取当前轮次记录索引
      const currentRoundIndex = interviewRounds.value.findIndex(r => r.round === currentRound.value);
      
      if (currentRoundIndex !== -1) {
        // 存储所有问题
        interviewRounds.value[currentRoundIndex].questions = questions.slice(0, 5);
        
        // 设置第一个问题
        if (questions.length > 0) {
          currentQuestion.value = questions[0];
          // 发送第一个问题
          await sendTextToAvatar(questions[0], currentRound.value);
        }
      }
    }
  } catch (error) {
    console.error('生成问题失败:', error);
    ElMessage.error('生成问题失败，请重试');
  }
}

// 获取大模型响应
const getModelResponse = async (text: string) => {
  try {
    // 构建对话历史
    const messages = [];
    
    // 添加系统提示
    messages.push({
      role: 'system',
      content: `你是专业面试官，正在对${jobInfo.value.jobName}职位的候选人进行面试。请严格遵守面试官行为模式。`
    });
    
    // 添加当前问题
    messages.push({ role: 'user', content: text });
    
    const data = {
      question: text,
      userId: 234,
      deepThinking: true, // 启用深度思考
      networkSearch: false,
      messages: messages
    };

    const response = await axios.post(API_ENDPOINTS.MODEL, data, {
      headers: { 'Content-Type': 'application/json' }
    });

    if (response.status === 200) {
      // 解析大模型返回的JSON
      const parsedResponse = parseModelResponse(response.data);
      
      // 提取content字段
      if (parsedResponse && parsedResponse.content) {
        return parsedResponse.content;
      }
      
      // 如果content字段不存在，返回原始数据
      return JSON.stringify(parsedResponse);
    }
    
    return text; // 如果请求失败，返回原始文本
  } catch (error) {
    console.error('获取大模型响应失败', error);
    return "请简单介绍一下你自己";
  }
};

// 解析大模型返回的JSON数据
const parseModelResponse = (response: any) => {
  try {
    // 尝试直接解析为JSON
    if (typeof response === 'string') {
      return JSON.parse(response);
    }
    return response;
  } catch (e) {
    // 如果解析失败，尝试提取可能的JSON部分
    try {
      const startIndex = response.indexOf('{');
      const endIndex = response.lastIndexOf('}') + 1;
      if (startIndex !== -1 && endIndex !== -1) {
        const jsonStr = response.substring(startIndex, endIndex);
        return JSON.parse(jsonStr);
      }
    } catch (parseError) {
      console.error('解析大模型返回失败', parseError);
    }
    
    // 如果无法解析，返回原始数据
    return { content: response };
  }
};

// 发送文本到数字人（添加轮次参数）
const sendTextToAvatar = async (text: string, round: number) => {
  try {
    const response = await axios.post(
      `${API_ENDPOINTS.TEXT}?round=${round}`, // 添加轮次参数
      text,
      {
        headers: { 'Content-Type': 'text/plain' }
      }
    );

    if (response.status === 200) {
      console.log('文本已发送给数字人');
    }
  } catch (error: any) {
    console.error('发送文本失败', error);
  }
};

// 解析推流信息
const parseStreamInfo = (message: any) => {
  try {
    // 处理不同类型的数据
    let data = message;
    if (typeof message === 'string') {
      try {
        data = JSON.parse(message);
      } catch (parseError) {
        console.error('JSON解析失败:', parseError);
        throw new Error('无效的JSON字符串');
      }
    }
    
    // 确保数据是对象
    if (typeof data !== 'object' || data === null) {
      throw new Error('推流信息必须是对象');
    }
    
    // 提取关键信息 - 根据新的JSON结构
    const avatarPayload = data.payload?.avatar;
    if (!avatarPayload) {
      throw new Error('推流信息缺少avatar字段');
    }
    
    const streamUrl = avatarPayload.stream_url;
    const userSign = avatarPayload.stream_extend?.user_sign;
    const appid = avatarPayload.stream_extend?.appid;
    
    if (!streamUrl || !userSign) {
      throw new Error('推流信息不完整');
    }
    
    // 解析stream_url - 处理xrtcs协议
    let urlStr = streamUrl;
    if (urlStr.startsWith('xrtcs://')) {
      urlStr = 'https://' + urlStr.substring(8);
    } else if (urlStr.startsWith('xrtc://')) {
      urlStr = 'http://' + urlStr.substring(7);
    }
    
    const url = new URL(urlStr);
    const server = `${url.protocol}//${url.host}`;
    const roomId = url.pathname.split('/').pop() || '';
    
    // 生成用户ID
    const userId = `user_${Math.random().toString(36).substr(2, 9)}`;
    
    return {
      sid: avatarPayload.cid || `vms_${Date.now()}`,
      server,
      auth: userSign,
      appid: appid || "1000000001",
      userId,
      roomId,
      timeStr: Date.now().toString(),
    };
  } catch (error) {
    console.error('解析推流信息失败:', error);
    return null;
  }
};

// 获取推流信息
const fetchStreamInfo = async () => {
  try {
    const response = await axios.get(API_ENDPOINTS.MESSAGE);
    
    if (response.data && response.data !== "No message received yet") {
      const info = parseStreamInfo(response.data);
      
      if (info) {
        streamInfo.value = info;
        return true;
      }
    }
    return false;
  } catch (error: any) {
    console.error('获取推流信息失败:', error);
    return false;
  }
};

// 启动轮询获取推流信息
const startPollingStreamInfo = () => {
  clearInterval(streamPolling.value);
  
  streamPolling.value = setInterval(async () => {
    const success = await fetchStreamInfo();
    
    if (success) {
      clearInterval(streamPolling.value);
      
      // 更新播放器配置
      if (player) {
        // 动态设置播放器属性
        (player as any).playerType = 12;
        (player as any).stream = streamInfo.value;
        player.play();
      } else {
        initPlayer();
      }
    }
  }, 1000); // 每秒轮询一次
};

// 恢复播放器
const resumePlayer = () => {
  if (player && typeof player.resume === 'function') {
    try {
      player.resume();
      showResumeButton.value = false;
    } catch (e) {
      console.error('恢复播放失败', e);
    }
  }
};

// 初始化播放器
const initPlayer = () => {
  if (!playerContainer.value) {
    return;
  }

  try {
    import("@/utils/rtcplayer2.1.3/rtcplayer.esm.js").then(({ RTCPlayer }) => {
      player = new RTCPlayer({}) as unknown as IRTCPlayer;
      
      // 设置监听事件
      player
        .on('play', () => console.log('播放器已启动'))
        .on('playing', () => console.log('playing事件'))
        .on('waiting', () => console.log('视频缓冲中...'))
        .on('error', (e: any) => console.error(`播放器错误: ${e.message || e}`))
        .on('not-allowed', () => {
          showResumeButton.value = true;
        });

      // 设置播放器属性
      (player as any).playerType = 12;
      
      if (streamInfo.value) {
        (player as any).stream = streamInfo.value;
      } else {
        // 默认配置
        (player as any).stream = {
          sid: "vms000ec4da@dx195f094539d6f19882",
          server: "https://xrtc-cn-east-2.xf-yun.com",
          auth: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIxMDAwMDAwMDAxIiwidGltZSI6MTY0ODAxODQ2MTU0MywiaWF0IjoxNjQ4MTkxMjQyfQ.CTcOh_kCLqvvglo5VLVnjgpZzoFpzk7Un3Et0c9dhUs",
          appid: "1000000001",
          userId: "123123123",
          roomId: "ase0001bbe2hu19632f0f6070442142",
          timeStr: Date.now().toString(),
        };
      }

      (player as any).videoSize = { width: 720, height: 1280 };
      (player as any).container = playerContainer.value;

      player.play();
    });
  } catch (e) {
    console.error('播放器初始化失败', e);
  }
};

// 组件卸载时清理资源
onUnmounted(() => {
  if (player) {
    try {
      player.destroy();
    } catch (e) {
      console.error('销毁播放器时出错', e);
    }
    player = null;
  }
  
  // 清除轮询定时器
  clearInterval(streamPolling.value);
  
  // 清理倒计时定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  // 清理媒体资源
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach(track => track.stop());
  }
});
</script>

<style scoped>
.el-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.control-panel {
  padding-right: 20px;
  height: 100%;
}

.control-card {
  height: 100%;
  border-radius: 12px;
  background: linear-gradient(to bottom, #ffffff 0%, #f8f9fa 100%);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  border: none;
  overflow-y: auto;
}

.controls {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.control-group {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
}

.action-btn {
  padding: 12px 20px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
}

.video-row {
  height: calc(100vh - 60px);
}

.camera-panel, .player-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  overflow: hidden;
  background: linear-gradient(to bottom, #ffffff 0%, #f8f9fa 100%);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  border: none;
}

.panel-header {
  background: linear-gradient(90deg, #3498db, #2c3e50);
  color: white;
  padding: 15px 20px;
  border-radius: 12px 12px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h3 {
  margin: 0;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.video-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000;
  position: relative;
  border-radius: 0 0 12px 12px;
  overflow: hidden;
  min-height: 500px; /* 确保容器有最小高度 */
}
.video-stream {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.player-container {
  width: 100%;
  height: 500px;  /* 添加固定高度 */
  background-color: #000;
  border-radius: 4px;
  overflow: hidden;
}

.placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #a0aec0;
  height: 100%;
  width: 100%;
  background: #1a202c;
}

.placeholder p {
  margin-top: 15px;
  font-size: 16px;
}

.question-card {
  background: #f0f7ff;
  border-radius: 10px;
  padding: 15px;
  margin-top: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.question-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 12px;
  color: #2c3e50;
}

.current-question {
  font-size: 16px;
  line-height: 1.6;
  padding: 15px;
  background: white;
  border-radius: 8px;
  min-height: 100px;
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.05);
}

.report-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  max-height: 400px;
  overflow-y: auto;
}

.report-header {
  color: #2c3e50;
  border-bottom: 1px solid #e2e8f0;
  padding-bottom: 10px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.round-report {
  margin-bottom: 25px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 15px;
  background: #f8fafc;
}

.round-title {
  color: #3498db;
  padding-bottom: 10px;
  border-bottom: 1px dashed #cbd5e0;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.report-item {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.question-block, .answer-block, .expression-analysis {
  display: flex;
  margin-bottom: 15px;
  gap: 12px;
}

.q-icon, .a-icon, .e-icon {
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #2196f3;
  font-size: 18px;
}

.a-icon {
  background: #e8f5e9;
  color: #4caf50;
}

.e-icon {
  background: #f3e5f5;
  color: #9c27b0;
}

.q-content, .a-content, .e-content {
  flex: 1;
}

.expression-analysis {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 12px;
  margin-top: 10px;
}

.snapshot-image {
  max-width: 100%;
  border-radius: 6px;
  margin-top: 10px;
  max-height: 200px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 恢复播放按钮样式 */
.resume-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.7);
  z-index: 100;
}

.header {
  position: relative;
}

/* 轮次控制对话框样式 */
.round-control-content {
  padding: 20px;
}

.round-summary {
  margin: 20px 0;
}

.summary-card {
  border-radius: 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: none;
}

.summary-content {
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #2c3e50;
}

.summary-item i {
  font-size: 24px;
  color: #3498db;
}

.next-round-control {
  margin: 30px 0;
  text-align: center;
}

.next-round-control h3 {
  margin-bottom: 20px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.interval-selector {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  align-items: center;
}

.final-report {
  text-align: center;
  padding: 30px 0;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 12px;
  margin: 20px 0;
}

.final-report h3 {
  color: #1565c0;
  margin-bottom: 15px;
}

/* 轮次指示器样式 */
.round-indicator {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  padding: 10px;
  background: #f0f7ff;
  border-radius: 50px;
}

.round-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  font-weight: bold;
  color: #7f8c8d;
  transition: all 0.3s ease;
}

.round-circle.active {
  background: #3498db;
  color: white;
  transform: scale(1.1);
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.3);
}

.round-circle.completed {
  background: #2ecc71;
  color: white;
}

.round-label {
  position: absolute;
  bottom: -25px;
  font-size: 12px;
  white-space: nowrap;
  color: #7f8c8d;
  font-weight: normal;
}

.round-circle.active .round-label,
.round-circle.completed .round-label {
  color: #2c3e50;
  font-weight: 500;
}

/* 对话框按钮样式 */
.report-btn {
  background: linear-gradient(135deg, #3498db 0%, #2c3e50 100%);
  border: none;
  color: white;
  font-weight: 500;
}

.next-btn {
  background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
  border: none;
  color: white;
  font-weight: 500;
}

.finish-btn {
  background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%);
  border: none;
  color: white;
  font-weight: 500;
}

/* 问题计数器样式 */
.question-count-tag {
  margin-left: 8px;
  font-weight: bold;
}

/* 语音评测结果样式 */
.evaluation-result-container {
  padding: 20px;
}

.score-summary {
  margin-bottom: 25px;
}

.total-score-box {
  background: linear-gradient(135deg, #f0f7ff 0%, #e1f0ff 100%);
  border-radius: 12px;
  padding: 20px;
  margin: 25px auto;
  text-align: center;
  max-width: 300px;
  border: 1px solid #d0e3ff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.total-score-label {
  font-size: 18px;
  color: #555;
  margin-bottom: 5px;
  font-weight: 600;
}

.total-score-value {
  font-size: 48px;
  font-weight: 700;
  color: #1a73e8;
  line-height: 1;
  margin: 10px 0;
}

.total-score-percentage {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

.result-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 40px;
  margin-top: 20px;
}

.chart-wrapper {
  width: 280px;
  height: 280px;
  position: relative;
}

.scores-detail {
  display: flex;
  flex-direction: column;
  gap: 15px;
  min-width: 200px;
}

.score-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.score-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
}

.score-indicator {
  width: 24px;
  height: 24px;
  border-radius: 6px;
  flex-shrink: 0;
}

.score-info {
  flex: 1;
}

.score-name {
  font-size: 16px;
  color: #555;
  margin-bottom: 3px;
  font-weight: 500;
}

.score-number {
  font-size: 22px;
  font-weight: 700;
  color: #333;
}

@media (max-width: 768px) {
  .result-content {
    flex-direction: column;
    gap: 30px;
  }
  
  .chart-wrapper {
    width: 250px;
    height: 250px;
  }
  
  .total-score-box {
    padding: 15px;
    max-width: 250px;
  }
  
  .total-score-value {
    font-size: 42px;
  }
  
  .score-item {
    padding: 12px 15px;
  }
  
  .score-number {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .total-score-value {
    font-size: 36px;
  }
  
  .chart-wrapper {
    width: 220px;
    height: 220px;
  }
}
</style>